import React, { useEffect, useState } from 'react';
import { Select } from 'antd';
import moment from 'moment';
import { ShowTimePicker } from '../index';

import styles from './index.less';

interface IProps {
  /**
   * 选择事件
   */
  onChange?: (values: {
    pendingTimeType?: number;
    pendingStartTime?: string;
    pendingEndTime?: string;
  }) => void;

  /**
   * 选项
   */
  options: { label: string; value: number }[];
  /**
   * 选择值
   */
  value?: {
    pendingTimeType?: number;
    pendingStartTime?: string;
    pendingEndTime?: string;
  };
}

const PendingTime = (props: IProps) => {
  const { onChange, value: _value, options } = props;
  const [pendingTimeType, setPendingTimeType] = useState<number>(1);
  const [pendingTime, setPendingTime] = useState<[moment.Moment, moment.Moment]>();

  useEffect(() => {
    if (_value) {
      setPendingTimeType(_value?.pendingTimeType || 1);
      setPendingTime(
        _value?.pendingStartTime && _value?.pendingEndTime
          ? [moment(_value?.pendingStartTime), moment(_value?.pendingEndTime)]
          : undefined,
      );
    }
  }, [_value]);

  const _onChange = (data: {
    pendingTimeType?: number;
    pendingStartTime?: string;
    pendingEndTime?: string;
  }) => {
    onChange && onChange(data);
  };

  const onChangePendingTimeType = (e: number) => {
    setPendingTimeType(e);
    const data = {
      pendingTimeType: e,
      pendingStartTime: pendingTime
        ? moment(pendingTime[0]).format('YYYY-MM-DD HH:mm:ss')
        : undefined,
      pendingEndTime: pendingTime
        ? moment(pendingTime[1]).format('YYYY-MM-DD HH:mm:ss')
        : undefined,
    };
    if (pendingTime) {
      _onChange(data);
    }
  };

  const onChangeTimePicker = (value: [moment.Moment, moment.Moment]) => {
    setPendingTime(value);
    const data = {
      pendingTimeType,
      pendingStartTime: value ? moment(value[0]).format('YYYY-MM-DD HH:mm:ss') : undefined,
      pendingEndTime: value ? moment(value[1]).format('YYYY-MM-DD HH:mm:ss') : undefined,
    };
    _onChange(data);
  };

  return (
    <div className={styles.container}>
      <Select
        options={options}
        onChange={onChangePendingTimeType}
        value={pendingTimeType}
        placeholder="请选择"
        style={{ marginRight: 12 }}
      />
      <ShowTimePicker
        type="rangePicker"
        value={pendingTime}
        format="HHmm"
        placeholder={['开始时间', '结束时间']}
        onChange={onChangeTimePicker}
      />
    </div>
  );
};

export default PendingTime;
